package com.itmg.taskmanager.bean;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.itmg.analyze.AnalyzeContext;
import com.itmg.cache.CacheContext;
import com.itmg.cache.SamplesModel;
import com.itmg.cache.StaticInformationBean;
import com.itmg.dao.CacheDAO;
import com.itmg.dao.CacheDataDAO;
import com.itmg.dao.bean.ConditionBean;
import com.itmg.dao.model.CacheDataModel;
import com.itmg.factory.DAOFactory;
import com.itmg.search.business.bean.SearchBean;
import com.itmg.tools.bean.PriceBean;
import com.itmg.tools.page.PageBean;
import com.itmg.tools.page.PageHandler;
import com.itmg.tools.thread.KeywordsSaveThread;
import com.itmg.util.Constants;
import com.itmg.util.MD5Util;
import com.itmg.vo.ModelCount;
import com.itmg.vo.SearchParameterVO;
import com.itmg.vo.SearchResultItemVO;
import com.itmg.vo.SearchResultVO;

public class SearchTaskBean {
	
	private static  AnalyzeContext analyzeContext = new AnalyzeContext();
	private static int totalResultNumber;
	public SearchTaskBean() {
	}
	
	//查询数据
	public static SearchResultVO getDataItemListByCondition(SearchParameterVO searchParameterVO,HttpServletRequest request) throws Exception
	{
		
		CacheDAO resultDAO = DAOFactory.getCacheDAO();
		ConditionBean conditionBean = null;
		PageBean page = searchParameterVO.getPage();
		String keyword = searchParameterVO.getKeyword();
		String category = searchParameterVO.getCategory();
		String sort = searchParameterVO.getSort();
		String isAuction = searchParameterVO.getIsAuction();
		SearchResultVO searchResultVO_new = new SearchResultVO();
		List<SearchResultItemVO> searchResult_temp = null;
		List<SearchResultItemVO> searchResult = new ArrayList<SearchResultItemVO>();
		String productMd5 = "";
		
		if(category != null && !"".equals(category)){
			if((searchParameterVO.getMinPrice() != null || searchParameterVO.getMaxPrice() != null) && !Constants.SORT_RELATIVE.equals(sort)){
				productMd5 = MD5Util.MD5(keyword+isAuction+category+Constants.SORT_RELATIVE);
			}else{
				productMd5 = MD5Util.MD5(keyword+isAuction+category+sort);
			}
		}else{
			if((searchParameterVO.getMinPrice() != null || searchParameterVO.getMaxPrice() != null) && !Constants.SORT_RELATIVE.equals(sort)){
				productMd5 = MD5Util.MD5(keyword+isAuction+Constants.SORT_RELATIVE);
			}else{
				productMd5 = MD5Util.MD5(keyword+isAuction+sort);
			}
		}
		
		//判断缓存中是否存在此Md5
		if(StaticInformationBean.getProductMd5(productMd5)){
			int count = 0;
			if(searchParameterVO.getMinPrice() != null || searchParameterVO.getMaxPrice() != null){
				conditionBean = new ConditionBean(productMd5,searchParameterVO.getMinPrice(),searchParameterVO.getMaxPrice());
				count = resultDAO.getCountByPrice(conditionBean);
			}
			else
				count = StaticInformationBean.getPagaTabel(productMd5);
			searchResultVO_new.setTotalResultNumber(StaticInformationBean.getTotal(productMd5));
			
			//分页信息
			page.setTotal(count);
			page = PageHandler.handle(page);
			conditionBean = new ConditionBean(keyword,category,productMd5,page.getOffset(), 
				page.getLength(),sort,searchParameterVO.getMinPrice(),searchParameterVO.getMaxPrice());
			searchResult = resultDAO.getCacheModelByProductMd5(conditionBean);
			
			//得到信息
			SearchTaskBean.getSearchInfo(productMd5,searchResultVO_new);
		}
		else{
			SearchResultVO searchResultVO = analyzeContext.getSearchResultItemVOList(searchParameterVO);
			searchResult_temp = searchResultVO.getResultItemList();
			CacheContext.sort(sort,searchResult_temp);//排序
			if(Constants.SORT_RELATIVE.equals(sort))
				Collections.shuffle(searchResult_temp);
			totalResultNumber = searchResultVO.getTotalResultNumber();
			conditionBean = new ConditionBean();
			conditionBean.setSearchResultItemList(searchResult_temp);
			conditionBean.setProductMd5(productMd5);
			conditionBean.setTotal(totalResultNumber);
			conditionBean.setSort(sort);
			conditionBean.setKeywords(keyword);
			conditionBean.setCreate_time(new Timestamp(System.currentTimeMillis()));
			StaticInformationBean.setProductMd5(productMd5);
			resultDAO.saveData(conditionBean);//缓存到数据库中
			
			//保存keywords信息
			if(!keyword.matches(Constants.REGEX_NUMBER))
				new Thread(new KeywordsSaveThread(conditionBean)).start();

			//设置信息
			SearchTaskBean.saveSearchInfo(searchResult_temp, searchParameterVO, productMd5,searchResultVO_new);
			
			//分页信息
			page.setTotal(searchResult_temp.size());
			page = PageHandler.handle(page);
			StaticInformationBean.setPageTable(productMd5, searchResult_temp.size());
			StaticInformationBean.setTotal(productMd5, totalResultNumber);
			if(searchResult_temp.size()>page.getLength()){
				searchResult = searchResult_temp.subList(page.getOffset(),page.getLength());
			}else{
				searchResult = searchResult_temp.subList(page.getOffset(),searchResult_temp.size());
			}
			searchResultVO_new.setTotalResultNumber(totalResultNumber);
		}
		searchResultVO_new.setResultItemList(searchResult);
		return searchResultVO_new;
	}
	
	//存储信息（型号，品牌，价格区间）
	@SuppressWarnings("null")
	private static void saveSearchInfo(List<SearchResultItemVO> list,SearchParameterVO vo,String productMd5,SearchResultVO searchResultVO_new) throws Exception{
		CacheDataDAO cacheDataDAO = DAOFactory.getCacheDataDAO();
		//BrandDAO brandDAO = DAOFactory.getBrandDAO();
		CacheDataModel model= new CacheDataModel();
		model.setProductMd5(productMd5);
		model.setKeywords(vo.getKeyword());
		model.setCategory(vo.getCategory());
		model.setCreate_time(new Timestamp(System.currentTimeMillis()));
		
	    //型号
		List<ModelCount> modelList = new ArrayList<ModelCount>();
		Hashtable<String,Integer> modelHash = SamplesModel.samplesProductModel(list,vo.getKeyword());
		String models = "";
		for(String mod : modelHash.keySet()){
			ModelCount modelCount = new ModelCount();
			models += mod+"("+modelHash.get(mod)+")" + ",";
			modelCount.setModel(mod);
			modelCount.setCount(modelHash.get(mod));
			modelList.add(modelCount);
		}
		if(modelList.size()==0)
			searchResultVO_new.setModelList(null);
		else
			searchResultVO_new.setModelList(modelList);
		model.setModel_name(models);
		
		/*//品牌
		List<String> brandList = new ArrayList<String>();
		Set<String> brandSet = SamplesModel.getBrand(list, brandDAO.getBrand());
		String brands = "";
		for(String mod : brandSet){
			brands += mod + ",";
			brandList.add(mod);
		}
		if(brandList.size()==0)
			searchResultVO_new.setBrandList(null);
		else
			searchResultVO_new.setBrandList(brandList);
		model.setBrand_name(brands);*/
		
		//价格区间
		List<PriceBean> priceList = SearchBean.priceProcessing(list);
		String prices = "";
		if(priceList != null || priceList.size()==0){
			for(PriceBean mod : priceList){
				if(mod.getMaxPrice() != null)
					prices += mod.getMinPrice()+Constants.REGEX_BO+mod.getMaxPrice() + Constants.REGEX_XIE;
				else
					prices += mod.getMinPrice();
			}
			if(priceList.size() == 0)
				searchResultVO_new.setPriceList(null);
			else
				searchResultVO_new.setPriceList(priceList);
			model.setPrice(prices);
			
			cacheDataDAO.saveInfo(model);
		}
	}
	
	//从数据库中得到型号和价格信息
	public static void getSearchInfo(String productMd5,SearchResultVO searchResultVO_new) throws Exception{
		List<ModelCount> modelList = new ArrayList<ModelCount>();
//		List<String> brandList = new ArrayList<String>();
		List<PriceBean> priceList = new ArrayList<PriceBean>();
		CacheDataDAO cacheDataDAO = DAOFactory.getCacheDataDAO();
		CacheDataModel model = cacheDataDAO.getInfo(productMd5);
		if(model.getModel_name() != null && !"".equals(model.getModel_name())){
			for(String value: model.getModel_name().split(",")){
				if(value != null && !"".equals(value)){
					int start = value.indexOf("(");
					String mod = value.substring(0,start);
					Integer count = Integer.parseInt(value.substring(start+1, value.length()-1));
					ModelCount modelCount = new ModelCount();
					modelCount.setModel(mod);
					modelCount.setCount(count);
					modelList.add(modelCount);
				}
				
			}
			searchResultVO_new.setModelList(modelList);
		}
		/*if(model.getBrand_name() != null && !"".equals(model.getBrand_name())){
			for(String value: model.getBrand_name().split(",")){
				brandList.add(value);
			}
			searchResultVO_new.setBrandList(brandList);
		}*/
		if(model.getPrice() != null && !"".equals(model.getPrice())){
			for(String value: model.getPrice().split(Constants.REGEX_XIE)){
				PriceBean bean = new PriceBean();
				if(value.contains(Constants.REGEX_BO)){
					String []price = value.split(Constants.REGEX_BO);
					bean.setMinPrice(Integer.parseInt(price[0]));
					bean.setMaxPrice(Integer.parseInt(price[1]));
				}else{
					bean.setMinPrice(Integer.parseInt(value));
				}
				priceList.add(bean);
			}
			searchResultVO_new.setPriceList(priceList);
		}
	}
	
//	public static SearchResultVO getDetailItemListByCondition(SearchParameterVO searchParameterVO,HttpServletRequest request) throws Exception
//	{
//		PageBean page = searchParameterVO.getPage();
//		String sort = searchParameterVO.getSort();
//		SearchResultVO searchResultVO_new = new SearchResultVO();
//
//		SearchResultVO searchResultVO = analyzeContext.getSearchResultItemVOList(searchParameterVO);
//		List<SearchResultItemVO> searchResult_temp = searchResultVO.getResultItemList();
////		totalResultNumber = searchResultVO.getTotalResultNumber();
//		HttpSession session = request.getSession();
//		session.setAttribute("detailItemList", searchResult_temp);
//		searchResultVO_new.setTotalResultNumber(searchResultVO.getTotalResultNumber());
//		
//		//缓存 排序
//		CacheContext.sort(sort,searchResult_temp);
//		List<SearchResultItemVO> searchResult = new ArrayList<SearchResultItemVO>();
//		try {
//			int pageLength = 0;
//			int total = searchResult_temp.size();
//			if (page != null) {
//				page.setTotal(total);
////				PageHandler.handle(page);
//				int offset = page.getOffset();
//				pageLength = page.getLength();
//				if (offset < 0)
//				{
//					offset = 0;
//				}
//				if (total == 0)
//				{
//					searchResultVO_new.setResultItemList(searchResult);
//					return searchResultVO_new;
//				}
//				int pageIndex = (offset/pageLength)+1; // 当面页码
//				int startindex = (pageIndex-1) * pageLength;
//				int endindex = (pageIndex-1)*pageLength + pageLength;
//				if(total < endindex)
//					endindex = total;
//				searchResult = searchResult_temp.subList(startindex, endindex);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		searchResultVO_new.setResultItemList(searchResult);
//		return searchResultVO_new;
//	}
}
